package com.xsr.realm;

import com.xsr.mapper.UserMapper;
import com.xsr.pojo.SysUsers;
import com.xsr.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;


import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project springMvcday03
 * @date 2022/9/14 17:28
 */
public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUsers primaryPrincipal = (SysUsers)principalCollection.getPrimaryPrincipal();
        int id = primaryPrincipal.getId();
        //用户具有的权限字符串
        List<String> perms = userService.findPerms(id);
        //用户具有的角色
        List<String> roles = userService.findRoles(id);
//        for (String role : roles) {
//            System.out.println(role.toString());
//        }
//        for (Object perm : perms) {
//            System.out.println(perm);
//        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(perms);
        authorizationInfo.addRoles(roles);


        return authorizationInfo;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String username =(String) authenticationToken.getPrincipal();
        char[] credentials = (char[])authenticationToken.getCredentials();
       String password=new String(credentials);
     SysUsers sysUsers1   =userMapper.selectUsername(username);
    if(sysUsers1==null){
        throw new UnknownAccountException("用户名不存在");
    }
   // SysUsers sysUsers2=    userMapper.selectUserAndName(username,password);
     if(!password.equals(sysUsers1.getPassword())){
         throw new IncorrectCredentialsException("密码不正确");
     }
        if(0==sysUsers1.getStatus()) {
            throw new LockedAccountException("账户被锁定");
        }
           AuthenticationInfo  authorizationInfo = new  SimpleAuthenticationInfo(sysUsers1,password,this.getName());
        return  authorizationInfo;
    }
}
